# -*- coding: utf-8 -*-
import re
import yaml
import os


def load_filter_config(config_file):
    """
    加载YAML格式的过滤配置文件
    如果配置文件不存在，则创建默认配置文件
    """
    try:
        with open(config_file, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        return config
    except Exception as e:
        print(f"读取配置文件时出错: {e}")
        return None


def filter_bookmarks_with_config(input_file, config):
    """
    根据YAML配置文件中的规则过滤书签文件内容
    只保留匹配规则的行，其他行过滤掉
    """
    # 读取输入文件
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # 过滤后的行
    filtered_lines = []

    # 获取过滤规则
    patterns = config.get('patterns', [])

    # 过滤掉注释和空行，只保留正则表达式模式
    regex_patterns = []
    for pattern in patterns:
        # 跳过注释和空字符串
        if isinstance(pattern, str) and not pattern.startswith('#') and pattern.strip() != '':
            regex_patterns.append(pattern)

    # 编译正则表达式以提高性能
    compiled_patterns = []
    for pattern in regex_patterns:
        try:
            compiled_patterns.append(re.compile(pattern))
        except re.error as e:
            print(f"正则表达式错误: {pattern}, 错误信息: {e}")
            continue

    # 处理每一行
    for line in lines:
        # 去除行尾换行符
        line_content = line.rstrip('\n')

        # 检查是否匹配任何规则
        matched = False
        for pattern in compiled_patterns:
            if pattern.match(line_content):
                matched = True
                break

        # 只保留匹配的行
        if matched:
            filtered_lines.append(line_content)

    return filtered_lines


def main():
    # 输入文件名
    INPUT_FILE = 'book_mark_in.txt'
    CONFIG_FILE = 'filter_bookmarks.yml'

    # 检查输入文件是否存在
    if not os.path.exists(INPUT_FILE):
        print(f"错误: 输入文件 {INPUT_FILE} 不存在")
        return

    # 加载配置文件
    config = load_filter_config(CONFIG_FILE)
    if config is None:
        print("无法加载配置文件，程序退出")
        return

    # 获取输出文件名
    OUTPUT_FILE = config.get('output_file', 'book_mark_filtered.txt')

    # 执行过滤
    filtered_lines = filter_bookmarks_with_config(INPUT_FILE, config)

    # 写入输出文件
    with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
        f.write('\n'.join(filtered_lines))

    # 读取原始文件行数
    with open(INPUT_FILE, 'r', encoding='utf-8') as f:
        original_lines = f.readlines()

    print(f"书签过滤完成！结果已保存到 {OUTPUT_FILE}")
    print(f"原始行数: {len(original_lines)}")
    print(f"过滤后行数: {len(filtered_lines)}")


if __name__ == "__main__":
    main()